package com.lmxdawn.api.dnf.util;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AesUtil {
    static final int KEY_LENGTH_BYTE = 32;
    static final int TAG_LENGTH_BIT = 128;
    private final byte[] aesKey;

    public AesUtil(byte[] key) {
        if (key.length != KEY_LENGTH_BYTE) {
            throw new IllegalArgumentException("无效的ApiV3Key，长度必须为32个字节");
        }
        this.aesKey = key;
    }

    public String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext)
            throws GeneralSecurityException, IOException {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);
            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            cipher.updateAAD(associatedData);
            return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            throw new IllegalArgumentException(e);
        }
    }


    public static void main(String[] args) throws GeneralSecurityException, IOException {
        String str = "NnJT2o/f/4JEemT2+BFfuSY+MduXJ/tTly1VhF4cwHNFdMEljJE17pdgEIZFMxInSfHfOVwq7bEv2ibF3HbUulIH/Dyd+ztSn1zZOvBYlDGy7PaJBve19Ep89/8PjTlfuG0CKIJqLSVki9bPgrqB8dqswFCLrQJuVA1ECpgEd0bNNSP4ennCTL6u7tZEu7e8MjPc3sC2uztwMlaeV4dYwue9SPWCU/CoUGQ/JAR2D7WPScLfAKLcKzj7eLImqyW7IQI8VBcXch9y2xOUZNChQ8pya8mzyh20NDDb32UZBnW6DLiaDiqb7yLXNusDf8KzniZH7z/LNgKZFOSqrnZ72WSOT0lXKMskDPMXlSTW2ZrYRzVcD5x6ivEiVkWuOeq+kCcvLbVDfFVuh3YXe8M/+xQ5wH8Xy3UtJVvX3TIJPRSt4NB3QyzZ/bELblz+Yy9rPZ8I215GvjMf18W9WVbYetex/ocJvdp4PLjgu1fEDcEI4fkF/2WSP/ic+Tm7EXgROxd7RB62x6jVmCTMMGfFowQKkK2NetTGjQM05wFpQ+S9/ChbBwhpq/A3wTA491qvRNUUwl24";

        AesUtil a = new AesUtil("Zxh1314Zxh1314Zxh1314Zxh1314Zxh1".getBytes());
        System.out.println(a.decryptToString("transaction".getBytes(), "6ZgV5e0EMYfa".getBytes(), str));

    }
}